package cn.itsource.org.controller;

import cn.itsource.org.domain.Product;
import cn.itsource.org.query.ProductQuery;
import cn.itsource.org.service.ProductService;
import cn.itsource.utli.AjaxResult;
import cn.itsource.utli.PageInfo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 商品控制层
 */
@RestController
@RequestMapping("/product")
public class ProductController {
    @Autowired
    private ProductService productService;
    /**
     * 查询全部
     * @return
     */
    @GetMapping
    public List<Product> getAll(){
        return productService.queryAll();
    }

    /**
     * 新增和修改
     * @param Product
     * @return
     */
    @PutMapping
    public AjaxResult saveOeUpdate(@RequestBody Product Product) {
        try {
            if (Product.getId() == null) {
                System.out.println(Product);
                productService.save(Product);
            } else {
                productService.update(Product);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage(e.getMessage());
        }
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public AjaxResult delete(@PathVariable("id") Long id) {
        try {
            productService.delete(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage(e.getMessage());
        }
    }

    /**
     * 查询单个数据
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Product queryById(@PathVariable("id") Long id) {
        return productService.queryById(id);
    }
    /**
     * 分页查询
     * @param query
     * @return
     */
    @PostMapping
    public PageInfo<Product> page(@RequestBody ProductQuery query) {
        return productService.queryPage(query);
    }
    
}
